﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.IO;
using System.Text;

namespace exsportance.Silverlight.Common.Utils
{
    public static class MiscUtils
    {
        /// <summary>
        /// Converts a stream to string
        /// </summary>
        /// <param name="stream"></param>
        /// <returns></returns>
        public static string GetAsString(this Stream stream)
        {
            MemoryStream memStream = new MemoryStream();

            byte[] respBuffer = new byte[1024];
            try
            {
                int bytesRead = stream.Read(respBuffer, 0, respBuffer.Length);
                if (bytesRead > 0)
                {
                    memStream.Write(respBuffer, 0, bytesRead);
                    bytesRead = stream.Read(respBuffer, 0, respBuffer.Length);
                }
            }
            finally
            {
                stream.Close();
            }

            return Encoding.UTF8.GetString(memStream.GetBuffer(), 0, (int)memStream.Length);
        }

        /// <summary>
        /// Returns the message and innerexception of this exception
        /// </summary>
        /// <param name="exception"></param>
        /// <returns></returns>
        public static string GetAsString(this Exception exception)
        {
            return GetAsString(exception, false);
        }

        /// <summary>
        /// Returns the message and innerexception of this exception
        /// </summary>
        /// <param name="exception"></param>
        /// <param name="includeStackTrace"></param>
        /// <returns></returns>
        public static string GetAsString(this Exception exception, bool includeStackTrace)
        {
            string result = exception.Message;

            if (result.IsNullOrEmpty() && exception.InnerException != null)
            {
                result = result.Add(exception.InnerException.Message);
            }

            if (includeStackTrace)
                result += "\r\n" + exception.StackTrace;

            return result;
        }
    }
}
